<template>
  <VcDialog v-bind="dialogProps" :visible="reVisible" key="AppImageViewer" @close="hide">
    <!-- CANVAS -->
    <div class="app-image-preview-canvas">
      <template v-for="(url, i) in urlList">
        <img
          v-if="i === index"
          ref="img"
          class="app-image-preview-img"
          :key="url"
          :src="currentImg"
          :style="imgStyle"
          @load="handleImgLoad"
          @error="handleImgError"
          @mousedown="handleMouseDown"
        />
      </template>
    </div>

    <!-- DOWNLOAD -->
    <div class="app-image-preview-button app-image-preview-download" @click="download">
      <a-icon type="download" />
    </div>

    <!-- CLOSE -->
    <div class="app-image-preview-button app-image-preview-close" @click="hide">
      <a-icon type="close-circle" />
    </div>

    <!-- ARROW -->
    <template v-if="!isSingle">
      <div class="app-image-preview-button app-image-preview-prev" :class="{ 'is-disabled': !infinite && isFirst }" @click="prev">
        <a-icon type="left" />
      </div>
      <div class="app-image-preview-button app-image-preview-next" :class="{ 'is-disabled': !infinite && isLast }" @click="next">
        <a-icon type="right" />
      </div>
    </template>

    <!-- ACTIONS -->
    <div class="app-image-preview-button app-image-preview-actions">
      <div class="app-image-preview-actions-inner">
        <a-icon type="zoom-out" @click="handleActions('zoomOut')"></a-icon>
        <a-icon type="zoom-in" @click="handleActions('zoomIn')"></a-icon>
        <i class="app-image-preview-actions-divider"></i>
        <a-icon :type="mode.icon" @click="toggleMode" />
        <i class="app-image-preview-actions-divider"></i>
        <a-icon type="undo" @click="handleActions('anticlocelise')" />
        <a-icon type="redo" @click="handleActions('clocelise')" />
      </div>
    </div>
  </VcDialog>
</template>

<script>
// ref: https://github.com/ElemeFE/element/blob/dev/packages/image/src/image-viewer.vue
import { ConfigConsumerProps } from 'ant-design-vue/es/config-provider'
import { isFF as isFirefox } from 'ant-design-vue/es/_util/env'
import { default as rafThrottle } from 'ant-design-vue/es/_util/throttleByAnimationFrame'
import VcDialog from 'ant-design-vue/es/vc-dialog'

let mousePosition = null
// ref: https://github.com/ant-design/ant-design/issues/15795
const getClickPosition = e => {
  mousePosition = {
    x: e.pageX,
    y: e.pageY
  }
  // 100ms 内发生过点击事件，则从点击位置动画展示
  // 否则直接 zoom 展示
  // 这样可以兼容非点击方式展开
  setTimeout(() => (mousePosition = null), 100)
}

// 只有点击事件支持从鼠标位置动画展开
if (typeof window !== 'undefined' && window.document && window.document.documentElement) {
  document.documentElement.addEventListener('click', getClickPosition, true)
}

const extension = src => {
  const index = src.lastIndexOf('.')
  const ext = ~index ? src.slice(index + 1) : ''
  return ext.toLowerCase()
}

const toBase64 = async url => {
  return new Promise(resolve => {
    const type = extension(url) || 'png'
    const img = new Image()
    let dataURL = 'Error: 抱歉，当前浏览器无法提供下载.'
    img.crossOrigin = 'Anonymous'
    img.src = url + '?v=' + Math.random()
    img.onload = () => {
      const c = document.createElement('canvas')
      const { width: w, height: h } = img

      c.width = w
      c.height = h

      c.getContext('2d').drawImage(img, 0, 0, w, h)

      try {
        dataURL = c.toDataURL(`image/${ type }`, 1)
      } catch (e) {
        //
        console.error(e)
      }
      resolve(dataURL)
    }
    img.onerror = () => {
      resolve(dataURL)
    }
  })
}

const Mode = {
  CONTAIN: {
    name: 'contain',
    icon: 'fullscreen'
  },
  ORIGINAL: {
    name: 'original',
    icon: 'fullscreen-exit' // interaction
  }
}

const mousewheelEventName = isFirefox ? 'DOMMouseScroll' : 'mousewheel'

const on = (element, type, callback) => {
  element && element.addEventListener(type, callback, false)
}

const off = (element, type, callback) => {
  element && element.removeEventListener(type, callback, false)
}

export default {
  name: 'ProImageViewer',

  components: { VcDialog },

  inheritAttrs: false,

  model: {
    prop: 'visible',
    event: 'change'
  },

  inject: {
    configProvider: { default: () => ConfigConsumerProps }
  },

  props: {
    urlList: {
      type: Array,
      default: () => []
    },
    zIndex: {
      type: Number,
      default: 2000
    },
    onSwitch: {
      type: Function,
      default: () => {}
    },
    onClose: {
      type: Function,
      default: () => {}
    },
    initialIndex: {
      type: Number,
      default: 0
    },
    initialFileName: String,
    visible: Boolean
  },

  data() {
    return {
      index: this.initialIndex,
      isShow: false,
      infinite: true,
      loading: false,
      mode: Mode.CONTAIN,
      transform: {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      },
      // extra
      dialogProps: {
        transitionName: 'zoom',
        maskTransitionName: 'fade',
        closable: false,
        keyboard: true,
        prefixCls: 'app-image-preview',
        mask: true,
        afterClose: this.onAfterClose,
        mousePosition
      }
    }
  },
  computed: {
    isSingle() {
      return this.urlList.length <= 1
    },
    isFirst() {
      return this.index === 0
    },
    isLast() {
      return this.index === this.urlList.length - 1
    },
    currentImg() {
      return this.urlList[this.index]
    },
    imgStyle() {
      const { scale, deg, offsetX, offsetY, enableTransition } = this.transform
      const style = {
        transform: `scale(${ scale }) rotate(${ deg }deg)`,
        transition: enableTransition ? 'transform .3s' : '',
        'margin-left': `${ offsetX }px`,
        'margin-top': `${ offsetY }px`
      }
      if (this.mode === Mode.CONTAIN) {
        style.maxWidth = style.maxHeight = '100%'
      }
      return style
    },
    reVisible: {
      set(value) {
        this.$emit('change', value)
      },
      get() {
        return this.visible
      }
    }
  },
  watch: {
    initialIndex(val) {
      this.index = val
    },
    index(val) {
      this.reset()
      this.onSwitch(val)
    },
    currentImg() {
      this.$nextTick(() => {
        const $img = this.$refs.img && this.$refs.img[0]
        if ($img && !$img.complete) {
          this.loading = true
        }
      })
    }
  },
  mounted() {
    this.deviceSupportInstall()
    // add tabindex then wrapper can be focusable via Javascript
    // focus wrapper so arrow key can't cause inner scroll behavior underneath
    // this.$refs['wrapper'].focus();
  },
  updated() {
    this.deviceSupportUninstall()
    this.deviceSupportInstall()
  },
  methods: {
    hide() {
      this.deviceSupportUninstall()
      this.onClose()
      this.reVisible = false
    },
    async download() {
      const src = this.urlList[this.index]
      const url = await toBase64(src)
      if (url.startsWith('Error')) {
        this.$message.warning(url.slice(7))
        return
      }
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.download = this.initialFileName || 'default-image'
      src && link.click()
    },
    deviceSupportInstall() {
      this._keyDownHandler = rafThrottle(e => {
        const keyCode = e.keyCode
        switch (keyCode) {
          // ESC
          case 27:
            this.hide()
            break
          // SPACE
          case 32:
            this.toggleMode()
            break
          // LEFT_ARROW
          case 37:
            this.prev()
            break
          // UP_ARROW
          case 38:
            this.handleActions('zoomIn')
            break
          // RIGHT_ARROW
          case 39:
            this.next()
            break
          // DOWN_ARROW
          case 40:
            this.handleActions('zoomOut')
            break
          default:
            break
        }
      })
      this._mouseWheelHandler = rafThrottle(e => {
        const delta = e.wheelDelta ? e.wheelDelta : -e.detail
        if (delta > 0) {
          this.handleActions('zoomIn', {
            zoomRate: 0.015,
            enableTransition: false
          })
        } else {
          this.handleActions('zoomOut', {
            zoomRate: 0.015,
            enableTransition: false
          })
        }
      })
      on(document, 'keydown', this._keyDownHandler)
      on(document, mousewheelEventName, this._mouseWheelHandler)
    },
    deviceSupportUninstall() {
      off(document, 'keydown', this._keyDownHandler)
      off(document, mousewheelEventName, this._mouseWheelHandler)
      this._keyDownHandler = null
      this._mouseWheelHandler = null
    },
    handleImgLoad() {
      this.loading = false
    },
    handleImgError(e) {
      this.loading = false
      e.target.alt = '加载失败'
    },
    handleMouseDown(e) {
      if (this.loading || e.button !== 0) return

      const { offsetX, offsetY } = this.transform
      const startX = e.pageX
      const startY = e.pageY
      this._dragHandler = rafThrottle(ev => {
        this.transform.offsetX = offsetX + ev.pageX - startX
        this.transform.offsetY = offsetY + ev.pageY - startY
      })
      on(document, 'mousemove', this._dragHandler)
      on(document, 'mouseup', () => {
        off(document, 'mousemove', this._dragHandler)
      })

      e.preventDefault()
    },
    reset() {
      this.transform = {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      }
    },
    toggleMode() {
      if (this.loading) return

      const modeNames = Object.keys(Mode)
      const modeValues = Object.values(Mode)
      const index = modeValues.indexOf(this.mode)
      const nextIndex = (index + 1) % modeNames.length
      this.mode = Mode[modeNames[nextIndex]]
      this.reset()
    },
    prev() {
      if (this.isFirst && !this.infinite) return
      const len = this.urlList.length
      this.index = (this.index - 1 + len) % len
    },
    next() {
      if (this.isLast && !this.infinite) return
      const len = this.urlList.length
      this.index = (this.index + 1) % len
    },
    handleActions(action, options = {}) {
      if (this.loading) return
      const { zoomRate, rotateDeg, enableTransition } = {
        zoomRate: 0.2,
        rotateDeg: 90,
        enableTransition: true,
        ...options
      }
      const { transform } = this
      switch (action) {
        case 'zoomOut':
          if (transform.scale > 0.2) {
            transform.scale = parseFloat((transform.scale - zoomRate).toFixed(3))
          }
          break
        case 'zoomIn':
          transform.scale = parseFloat((transform.scale + zoomRate).toFixed(3))
          break
        case 'clocelise':
          transform.deg += rotateDeg
          break
        case 'anticlocelise':
          transform.deg -= rotateDeg
          break
        default:
          break
      }
      transform.enableTransition = enableTransition
    },
    onAfterClose() {
      this.index = this.initialIndex
      this.reset()
    }
  }
}
</script>

<style lang="less">
@import "~ant-design-vue/lib/style/themes/default";

@image-preview-operation-color: @text-color-dark;
@image-preview-operation-disabled-color: fade(@image-preview-operation-color, 45%);

.app-image-preview {
  pointer-events: none;
  height: 100%;
  text-align: center;

  &-body {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
  }

  &-wrap {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1000;
    overflow: auto;
    outline: 0;
    -webkit-overflow-scrolling: touch;
  }

  &-mask {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1000;
    height: 100%;
    background-color: rgba(0,0,0,.45);
  }

  &-button {
    position: absolute;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    opacity: .8;
    cursor: pointer;
    box-sizing: border-box;
    user-select: none;
    pointer-events: auto;
  }

  &-download {
    top: 40px;
    right: 100px;
    width: 40px;
    height: 40px;
    font-size: 40px;
  }

  &-close {
    top: 40px;
    right: 40px;
    width: 40px;
    height: 40px;
    font-size: 40px;
  }

  &-canvas {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    pointer-events: auto;

    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }

  &-actions {
    left: 50%;
    bottom: 30px;
    transform: translateX(-50%);
    width: 282px;
    height: 44px;
    padding: 0 23px;
    background-color: #606266;
    border-color: #fff;
    border-radius: 22px;
  }

  &-actions-inner {
    width: 100%;
    height: 100%;
    text-align: justify;
    cursor: default;
    font-size: 23px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }

  &-prev {
    top: 50%;
    transform: translateY(-50%);
    width: 44px;
    height: 44px;
    font-size: 24px;
    color: #fff;
    background-color: #606266;
    border-color: #fff;
    left: 40px;

    &.is-disabled {
      color: @image-preview-operation-disabled-color;
      cursor: not-allowed;
    }
  }

  &-next {
    top: 50%;
    transform: translateY(-50%);
    width: 44px;
    height: 44px;
    font-size: 24px;
    color: #fff;
    background-color: #606266;
    border-color: #fff;
    right: 40px;
    text-indent: 2px;

    &.is-disabled {
      color: @image-preview-operation-disabled-color;
      cursor: not-allowed;
    }
  }
}
</style>
